package com.medical.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.medical.common.core.domain.Result;
import com.medical.common.security.utils.SecurityUtils;
import com.medical.manage.domain.Comments;
import com.medical.manage.mapper.CommentsMapper;
import com.medical.manage.service.CommentsService;
import com.medical.system.domain.LoginUser;
import com.medical.system.domain.SysUser;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentsServiceImpl extends ServiceImpl<CommentsMapper, Comments> implements CommentsService {

    /**
     * 评论
     * @return
     */
    @Override
    public Result getComment(Integer id) {
        //先查询一级评论
        LambdaQueryWrapper<Comments> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comments::getPid,0);
        queryWrapper.eq(Comments::getArticleId,id);
        List<Comments> oneList = this.list(queryWrapper);
        getOneList(oneList);
        return Result.success(oneList);
    }

    public void getOneList(List<Comments> oneList){
        LambdaQueryWrapper<Comments> queryWrapper = new LambdaQueryWrapper<>();
        //遍历要同步的数据
        oneList.forEach(oneComment->{
            //获取一级评论的id
            Integer commentsId = oneComment.getId();
            //将一级评论的id作为下一级的父id
            queryWrapper.eq(Comments::getPid, commentsId);
            List<Comments> twoList = this.list(queryWrapper);
            //将二级评论放入一级评论里
            oneComment.setCommentsList(twoList);
        });
    }

    /**
     * 发布评论
     * @param comments
     */
    @Override
    public void publishComment(Comments comments) {
        //获取发布人id
        Long userId = SecurityUtils.getUserId();
        comments.setUserId(userId);
        save(comments);
    }
}